package com.maxmind.controller;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.maxmind.common.BusinessException;
import com.maxmind.common.Response;
import com.maxmind.common.validate.ResCode;
import com.maxmind.service.LookUpService;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * 类LookUpController的实现描述：地址查询controller
 *
 * @author sunyj 2025/3/21 14:14
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/lookUp")
public class LookUpController {

    private final LookUpService lookUpService;
    private final ThreadPoolTaskExecutor taskExecutor;

    public LookUpController(LookUpService lookUpService,
                            @Qualifier("ipLookupExecutor") ThreadPoolTaskExecutor taskExecutor) {
        this.lookUpService = lookUpService;
        this.taskExecutor = taskExecutor;
    }

    @GetMapping("/getResultByIpStr")
    public CompletableFuture<Response> getResultByIpStrAsync(@RequestParam String ip) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                return Response.builderSuccess(lookUpService.getResultByIpStr(ip));
            } catch (BusinessException e) {
                log.warn("Business error for IP {}: {}", ip, e.getMessage());
                return Response.builderFail(e.getCode(), e.getMessage());
            } catch (Exception e) {
                log.error("System error for IP {}: {}", ip, e.getMessage(), e);
                return Response.builderFail(ResCode.ORDER_ERROR_1003, ResCode.ORDER_ERROR_1003_DESC);
            }
        }, taskExecutor);
    }
}
